import { Position, useVueFlow } from "@vue-flow/core";

export function useSnakeLayout() {
  const { findNode } = useVueFlow();

  function applySnakeLayout(nodes, devicesPerRow = 5, containerWidth = 900, horizontalSpacing = 200, verticalSpacing = 200) {
    const nodeWidth = 250;
    const nodeHeight = 50;
    const rowWidth = devicesPerRow * nodeWidth + (devicesPerRow - 1) * horizontalSpacing;
    // const offsetX = (containerWidth - rowWidth) / 2;
    const offsetX = 50;
    const offsetY = 30;
    let layoutedNodes = [];
    let direction = 1;

    for (let i = 0; i < nodes.length; i++) {
      const row = Math.floor(i / devicesPerRow);
      const colInRow = i % devicesPerRow;
      const realIndexInRow = direction === 1 ? colInRow : (devicesPerRow - 1 - colInRow);

      const x = offsetX + realIndexInRow * (nodeWidth + horizontalSpacing);
      const y = row * (nodeHeight + verticalSpacing) + offsetY;

      // 判断连接方向（跟行的方向一致）
      let sourcePosition = direction === 1 ? Position.Right : Position.Left;
      let targetPosition = direction === 1 ? Position.Left : Position.Right;

      layoutedNodes.push({
        ...nodes[i],
        position: { x, y },
        // position: nodes[i].position ?? { x, y }, // ✅ 如果已有 position 就用原来的
        sourcePosition,
        targetPosition,
        draggable: nodes[i].draggable ?? (nodes[i].position ? false : true), // 🔒禁止拖动
      });

      // 如果到达本行最后一个节点，就准备反转方向
      if ((i + 1) % devicesPerRow === 0) {
        direction *= -1;
      }
    }

    return layoutedNodes;
  }

  return { applySnakeLayout };
}
